package com.gxnu.edu.cn.ttxxt.controller;

import com.gxnu.edu.cn.ttxxt.entity.ChatGroups;
import com.gxnu.edu.cn.ttxxt.entity.GroupsMembers;
import com.gxnu.edu.cn.ttxxt.service.GroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import static java.lang.Long.parseLong;

@RestController
@RequestMapping("/api/groups")
public class GroupController {

    @Autowired
    private GroupService groupService;

    @PostMapping("/")
    public ResponseEntity<ChatGroups> createGroup(@RequestBody Map<String, String> request) {
        Long creatorId = Long.parseLong(request.get("creatorId"));
        String groupName = request.get("groupName");
        String description = null;

        ChatGroups group = groupService.createGroup(creatorId, groupName, description);
        return ResponseEntity.ok(group);
    }

    @PostMapping("/{groupId}/members")
    public ResponseEntity<?> addMember(@PathVariable Long groupId, @RequestBody Map<String, Long> request) {
        Long userId = request.get("userId");
        Integer role = Math.toIntExact(request.get("role"));

        groupService.addMember(groupId, userId, role);
        return ResponseEntity.ok("成员已添加");
    }

    @DeleteMapping("/{groupId}/members/{userId}")
    public ResponseEntity<?> removeMember(@PathVariable Long groupId, @PathVariable Long userId) {
        groupService.removeMember(groupId, userId);
        return ResponseEntity.ok("成员已移除");
    }

    @PutMapping("/{groupId}/members/{userId}/role")
    public ResponseEntity<?> updateMemberRole(@PathVariable Long groupId, @PathVariable Long userId,
                                              @RequestBody Map<String, Integer> request) {
        Integer role = request.get("role");
        groupService.updateMemberRole(groupId, userId, role);
        return ResponseEntity.ok("成员角色已更新");
    }

    // 服务器端Controller方法
    @DeleteMapping("/{groupId}")
    public ResponseEntity<Map<String, Object>> dissolveGroup(
            @PathVariable Long groupId,
            @RequestBody Map<String, Long> request
    ) {
        try {
            Long operatorId = request.get("operatorId");
            if (operatorId == null) {
                return ResponseEntity.badRequest()
                        .body(Collections.singletonMap("error", "缺少operatorId参数"));
            }

            groupService.dissolveGroup(groupId, operatorId);

            return ResponseEntity.ok(Collections.singletonMap(
                    "status", "200"
            ));
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                    .body(Collections.singletonMap("error", e.getMessage()));
        }
    }

    @GetMapping("/name")
    public ResponseEntity<ChatGroups> getGroupByName(@RequestParam String groupName, @RequestParam Long operatorId) {
        if (operatorId == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); // 操作者ID不能为空
        }
        ChatGroups group = groupService.dissolveGroupName(groupName, operatorId);
        if (group == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); // 群组未找到
        }
        return ResponseEntity.ok(group);
    }

    @GetMapping("/user/{userId}")
    public ResponseEntity<List<ChatGroups>> getUserGroups(@PathVariable Long userId) {
        List<ChatGroups> groups = groupService.getUserGroups(userId);
        return ResponseEntity.ok(groups);
    }

    @GetMapping("/userjoin/{userId}")
    public ResponseEntity<List<ChatGroups>> getUserJoinGroups(@PathVariable Long userId) {
        List<ChatGroups> groups = groupService.getUserJoinGroups(userId);
        return ResponseEntity.ok(groups);
    }

    @GetMapping("/{groupId}/members")
    public ResponseEntity<List<GroupsMembers>> getGroupMembers(@PathVariable Long groupId) {
        List<GroupsMembers> members = groupService.getGroupMembers(groupId);
        return ResponseEntity.ok(members);
    }

    @GetMapping("/{groupId}")
    public ResponseEntity<ChatGroups> getGroupInfo(@PathVariable Long groupId) {
        ChatGroups group = groupService.getGroupInfo(groupId);
        return ResponseEntity.ok(group);
    }

    @PostMapping("/apply")
    public ResponseEntity<?> applyToJoinGroup(@RequestBody Map<String, Object> request) {
        Long userId = parseLong(request.get("userId").toString());
        Long groupId = parseLong(request.get("groupId").toString());
        String message = String.valueOf(request.get("message"));

        groupService.applyToJoinGroup(userId, groupId, message);
        return ResponseEntity.ok("申请已提交");
    }
}